<template>
  <div class="c-h c-bg-sgray">
    <div :class="[drawerVisibility ? 'c-text-hidden':'',theme]" :drawer-style="{'background-color':'#fff', width: '38%'}">
      <div class="c-minh" :class="showNavBottomBar ? 'c-pb80 ':''">
        <div class="top-fixed">
          <div class="c-pv16 c-flex-row c-justify-sb c-aligni-center c-bg-white">
            <div class="c-flex-column c-aligni-center c-pr16 c-pl24" v-on:click='popMore'>
              <div class="c-fc-gray iconfont c-fs30">&#xe798;</div>
              <div class="c-fs18 c-fc-gray">归档</div>
            </div>
            <div class="c-flex-1">
              <new-search-bar @search="startSearch" @cancel="startSearch" :searchText="searchText"></new-search-bar>
            </div>
          </div>
          <my-small-tabbar id="tabhBar" :tabList="tabList" :tabIndex="datumType" @changeTab="changeType" tabNameClass="c-fs26" class="c-bg-white" v-if="showTabbar"></my-small-tabbar>
        </div>
        <div :class="curDatumId ? 'c-hh114' : 'c-hh210'"></div>
        <div class="c-flex-row c-justify-sb c-aligni-center c-ph24 c-pv20 c-bg-white c-fs28" v-if="showFileName">
          <div v-if="curDatumName">{{curDatumName}}</div>
          <div class="iconfont c-fc-sgray" @click="closeShowFile">&#xe6ec;</div>
        </div>
        <div class="c-bg-white" v-if="datumList != null && datumList.length > 0" :class="showFileName == true ? 'boxShdow' : ''">
          <div class="c-bd-b1 c-flex-row c-pv24 c-ph24" v-for="(item,index) in datumList" :key="index" @click="clickdatumItem(item.datumId)">
            <div class="c-ww180 c-hh120 c-br10 c-text-hidden c-p c-flex-shrink0">
              <CoverImg :coverSizeClass="'c-w100 c-h c-br16 c-text-hidden'" imgClass="c-br16" :coverUrl="$addXossFilter(item.datumCover, require('@/assets/defult270.png'))" />
              <vip-status :item="item"></vip-status>
            </div>
            <div class="c-pl20 c-flex-column c-justify-sb c-flex-grow1 c-w0 ">
              <div class="c-fs24 c-fc-xblack c-text-ellipsis1 c-pt5">{{item.name}}</div>
              <div class="c-pt10 c-flex-row c-aligni-center c-fs20 c-fc-gray c-pb5">
                <span class="c-flex-grow1 c-fs22 c-fw600 c-w0 c-fc-xmlred" v-if="item.permission == 19">免费</span>
                <span class="c-flex-grow1 c-fs22 c-fw600 c-w0 c-fc-xmlred" v-if="item.permission == 21">加密</span>
                <div class="c-flex-grow1 c-w0">
                  <span class="c-fc-xmlred c-fw600" v-if="item.permission != 19 && item.permission != 21">
                    <span class="c-fs20">{{'￥' | iosPriceFilter}}</span>
                    <span :class="checkCnPrice(item.payType, item.price, 8) ? 'c-fs22' : 'c-fs26'">{{item.payType | priceValueFilter(item.price, 8, item.optimal, 'index')}}</span>
                  </span>
                  <span v-if="isShowcrossedPrice(item)" class="c-fs18 c-fc-gray c-text-decoration-through c-ml10">￥{{getCrossedPrice(item)}}</span>
                </div>
                <span v-if="datumType == 'sale' && !$isWxAppIos()">已售{{item.sales}}件</span>
                <span v-else>{{item.downloadTimes}}次下载</span>
              </div>
            </div>
          </div>
        </div>
        <loading-status-tem :dataStatus="dataStatus" noDataText="暂无结果" class="imgCloseBig"></loading-status-tem>
      </div>

    </div>
    <cj-popup v-model="showSideList" position="bottom" round @opened="showPopup" @closed="hidePopup">
      <header class="c-mh24 c-hh86 c-flex-row c-aligni-center c-bd-b1">
        <span class="c-fs30 c-fw-b c-flex-grow1 c-w0">资料归档</span>
      </header>
      <article class="c-hh540 c-ph24 c-contexty-auto">
        <section @click="clickCate(index)" v-for="(item,index) in sideList" :key="index" class="c-hh80 c-fw400 c-flex-row c-aligni-center c-fs24 c-bd-b1" :class="curIndex == index ? 'theme-fc':''">
          {{item.name}}
        </section>
      </article>
    </cj-popup>
    <nav-bottom-bar :itemIndex="20" v-if="showNavBottomBar"></nav-bottom-bar>
  </div>
</template>

<script>
import newSearchBar from "@/components/templates/common/newSearchBar.vue"
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import NavBottomBar from "@/components/templates/common/navBottomBar.vue";
import MySmallTabbar from "@/components/templates/common/MySmallTabbar.vue";
import vipStatus from '@/components/templates/common/vipStatus.vue'
import CoverImg from '@/components/templates/common/coverImg.vue';
import { utilJs } from "@/utils/common.js";
const LIMIT = 10;
let pageIndex = 1;
let curScollTop = 0;
export default {
  name: "DatumList",
  components: {
    loadingStatusTem,
    NavBottomBar,
    MySmallTabbar,
    newSearchBar,
    vipStatus,
    CoverImg
  },
  props: [],
  data() {
    return {
      tabList: [
        { title: '最新', index: 'time' },
        { title: '畅销', index: 'sale' },
        { title: '推荐', index: 'hot' }
      ],
      theme: localStorage.getItem("colorName") ? localStorage.getItem("colorName") : 'mb5_default',
      themeName: localStorage.getItem('themeName') ? localStorage.getItem('themeName') : 'mb5',
      searchText: "",
      datumType: 'time',
      curIndex: -1, //当前点击分类 默认-1表示全部
      sideList: [],
      datumList: [],
      showNavBottomBar: false,
      companyAuth: localStorage.getItem("companyAuth") ? JSON.parse(localStorage.getItem("companyAuth")) : null,
      dataStatus: 'HAS_MORE_DATA',
      drawerVisibility: true,
      showSideList: false,
      showFileName: false, //是否显示归档名称
      showTabbar: true,
      curDatumName: '',
    };
  },
  computed: {
    // 判断显示划线价格
    isShowcrossedPrice() {
      return function(item) {
        return !this.$isWxAppIos() && item.crossedPrice && Number(item.crossedPrice) > 0;
      }
    },
    // 获取划线价格
    getCrossedPrice() {
      return function(item) {
        return item.crossedPrice;
      }
    }
  },
  created() {
    utilJs.appShare(this);
  },
  mounted() {
    this.wechatShare();
  },
  methods: {
    checkCnPrice(payType, price, prodType) {
      return utilJs.checkCnPrice(payType, price, prodType)
    },
    showPopup() {
      curScollTop = document.documentElement.scrollTop || document.body.scrollTop;
      document.querySelector('body').classList.add('open-disabled-scroll');
    },
    hidePopup() {
      document.querySelector('body').classList.remove('open-disabled-scroll');
      //关闭弹窗，恢复滚动位置
      window.scrollTo(0, curScollTop);
    },
    iosAppRouteChange(toPath) {
      if (utilJs.isIOSApp()) {
        window.webkit.messageHandlers.iosWechatRoute.postMessage(toPath);
      } else if (utilJs.isAndoridNewApp()) {
        let data = {
          path: toPath
        }
        window.androidWechatRoute.doAction(JSON.stringify(data))
      } else {
        this.$routerGo(this, "push", { path: toPath });
      }
    },
    changeType(typeName) {
      if (this.datumType != typeName) {
        pageIndex = 1;
        this.datumType = typeName;
        this.getDatumList();
      }
    },
    startSearch(e) {
      this.searchText = e.searchValue;
      this.datumList = [];
      pageIndex = 1;
      if (this.showFileName == true) {
        this.getDatumToCats();
      } else {
        this.getDatumList();
      }
    },
    clickdatumItem(datumId) {
      let toPath = `/homePage/datum/datumDetail?datumId=${datumId}`;
      this.iosAppRouteChange(toPath);
    },
    //点击分类
    clickCate(index) {
      this.showSideList = false;
      this.showFileName = true;
      this.showTabbar = false;
      this.curIndex = index;
      this.curDatumId = index == -1 ? "" : this.sideList[index].datumCatId;
      this.curDatumName = this.sideList[index].name;
      this.dataStatus = 'HAS_MORE_DATA';
      pageIndex = 1;
      this.datumList = [];
      this.getDatumToCats();
    },
    //获取资料库分类
    getDatumCate() {
      utilJs.getMethod(global.apiurl + "datum/cat", res => {
        this.sideList = res;
      });
    },
    //获取资料库列表
    getDatumList() {
      if (this.dataStatus == 'LOADING') {
        return;
      }
      this.dataStatus = 'LOADING';
      utilJs.getMethod(`${global.apiurl}datum/list?order=${this.datumType}&sort=0&datumName=${this.searchText}&limit=${LIMIT}&page=${pageIndex}&datumCatId=${this.curDatumId}`,
        res => {
          if (pageIndex == 1) {
            this.datumList = res.data;
          } else {
            this.datumList = [...this.datumList, ...res.data];
          }
          if (res.data && (res.data.length < LIMIT)) {
            this.dataStatus = pageIndex == 1 && res.data.length == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
          } else {
            this.dataStatus = 'HAS_MORE_DATA';
            pageIndex++;
          }
        },
        failRes => {
          this.dataStatus = 'DATA_ERROR';
        }
      );
    },
    getDatumToCats() {
      if (this.dataStatus == 'LOADING') {
        return;
      }
      this.dataStatus = 'LOADING';
      utilJs.getMethod(`${global.apiurl}datum/getDatumToCats/${this.curDatumId}?limit=${LIMIT}&page=${pageIndex}&datumName=${this.searchText}`, res => {
        if (this.curDatumId) {
          this.curDatumName = res.datumCatName;
        }
        if (pageIndex == 1) {
          this.datumList = res.data.data;
        } else {
          this.datumList = [...this.datumList, ...res.data.data];
        }
        if (res.data.data && (res.data.data.length < LIMIT)) {
          this.dataStatus = pageIndex == 1 && res.data.data.length == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
        } else {
          this.dataStatus = 'HAS_MORE_DATA';
          pageIndex++;
        }
      }, failRes => {
        this.dataStatus = 'DATA_ERROR';
      })
    },
    popMore() {
      this.showSideList = true
      // this.drawerVisibility = true;
    },
    closeShowFile() {
      this.showFileName = false;
      this.showTabbar = true;
      this.curIndex = -1;
      pageIndex = 1;
      this.curDatumId = "";
      this.datumList = [];
      this.getDatumList();
    },
    //分享
    wechatShare: function () {
      let title = '资料库列表';
      let shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?refereeId=${localStorage.getItem("userId")}`;
      utilJs.wechatConfig(shareUrl, title, "", "", function () { });
    },
    //手机端分享
    appShare: function () {
      let title = '资料库列表';
      let shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?refereeId=${localStorage.getItem("userId")}`;
      utilJs.appShareTrue(title, "", shareUrl, "");
    },
    windowScrollFunction() {
      utilJs.handleLoading(() => {
        if (this.dataStatus == 'HAS_MORE_DATA') {
          if (this.showFileName == true) {
            this.getDatumToCats();
          } else {
            this.getDatumList();
          }
        }
      });
    },
    initData() {
      pageIndex = 1;
      this.dataStatus = 'HAS_MORE_DATA';
      this.datumList = [];
      this.searchText = "";
      this.curIndex = -1;
      this.datumType = 'time';
      this.showFileName = false;
      this.showTabbar = true;
      this.curDatumName = "";
      this.curDatumId = this.$route.query.id || 0;
      if (this.curDatumId) {
        this.showFileName = true;
        this.showTabbar = false;
        this.getDatumToCats();
      } else {
        this.curDatumId = ""
        this.getDatumList();
      }
    },
  },
  activated() {
    setDocumentTitle("资料库列表");// eslint-disable-line
    // pageIndex = 1;
    // this.datumList = [];
    this.getDatumCate();
    if (utilJs.checkNeedInitData(this.datumList)) {
      this.initData()
    }
    this.companyAuth = JSON.parse(localStorage.getItem("companyAuth"));
    if (this.companyAuth.companyNav && this.companyAuth.companyNav.length > 0) {
      let arrDatumFilter = this.companyAuth.companyNav.filter((item) => {
        return item.navType == 20;
      });
      this.showNavBottomBar = arrDatumFilter.length > 0;
    }
    window.addEventListener('scroll', this.windowScrollFunction);
  },
  deactivated() {
    // this.dataStatus = 'NO_MORE_DATA';
    window.removeEventListener('scroll', this.windowScrollFunction);
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style scoped>
.c-w90 /deep/ .c-ph24 {
  padding: 0;
}
.boxShdow {
  box-shadow: 0px 1px 5px 0px rgba(0,0,0,0.10);
}
.top-fixed {
  position: fixed;
  z-index: 11;
  width: 100%;
  max-width: 640px;
  background: #fff;
}
#tabhBar {
  padding-bottom: .5rem;
}
</style>
